import { createResolvablePromise, UUID } from '@/utils/common'
import {
  Button,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  useDisclosure,
} from '@heroui/react'
import { forwardRef, useImperativeHandle, useRef, useState } from 'react'
import Cropper, { ReactCropperElement } from 'react-cropper'
import 'cropperjs/dist/cropper.css'

export interface ModalRef {
  show: (params: ShowParams) => Promise<ResultType>
}
interface Props {}
type ResultType = {
  imageUrl: string
  canvas: HTMLCanvasElement
}
interface ShowParams {
  imageUrl: string
  clipProportion: {
    width: number
    height: number
  }
}
const title = `图片裁剪`
const ImageClip = ({}: Props, ref: React.Ref<ModalRef>) => {
  const { isOpen, onOpen, onClose } = useDisclosure()
  const [confirmLoading, setConfirmLoading] = useState(false)
  const [currentImageUrl, setCurrentImageUrl] = useState('')
  const [aspectRatio, setAspectRatio] = useState(1)
  const submitResolve = useRef<(r: ResultType) => void>(null)
  const cropperRef = useRef<ReactCropperElement>(null)
  useImperativeHandle(ref, () => ({
    show: (data: ShowParams) => {
      const [p, resolve] = createResolvablePromise()
      submitResolve.current = resolve
      setCurrentImageUrl(data.imageUrl)
      setAspectRatio(data.clipProportion.width / data.clipProportion.height)
      onOpen()
      return p
    },
  }))
  const onSubmit = () => {
    setConfirmLoading(true)
    try {
      const result: ResultType = {
        imageUrl: '',
        canvas: null,
      }
      if (cropperRef.current) {
        const canvas = cropperRef.current.cropper.getCroppedCanvas()
        if (canvas) {
          result.imageUrl = canvas.toDataURL('image/png')
          result.canvas = canvas
        }
      }
      onClose()
      submitResolve.current(result)
    } finally {
      setConfirmLoading(false)
    }
  }
  return (
    <Modal title={title} isOpen={isOpen} onClose={onClose} className="dark">
      <ModalContent>
        {(_onClose) => {
          return (
            <>
              <ModalHeader>图片裁剪</ModalHeader>
              <ModalBody>
                <div style={{ width: '100%', padding: '16px' }}>
                  {isOpen && (
                    <Cropper
                      key={UUID()}
                      ref={cropperRef}
                      src={currentImageUrl}
                      aspectRatio={aspectRatio}
                      style={{ width: '100%', height: '400px' }}
                      guides={true}
                      viewMode={1}
                      dragMode="move"
                      cropBoxMovable={true}
                      cropBoxResizable={true}
                    />
                  )}
                </div>
              </ModalBody>
              <ModalFooter>
                <Button
                  isLoading={confirmLoading}
                  onPress={onSubmit}
                  size="sm"
                  color="primary"
                  style={{
                    color: 'white',
                  }}>
                  裁剪
                </Button>
              </ModalFooter>
            </>
          )
        }}
      </ModalContent>
    </Modal>
  )
}

export default forwardRef<ModalRef, Props>(ImageClip)
